<?php
/**
 * @ClassName: CustomerLogic
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-11-03 17:33
 * @Version: V1.0.0
 */

namespace app\common\logic;

use app\common\model;
use think\Db;
use think\Exception;

class CustomerLogic
{
    /**
     * 创建客户
     * @param $username
     * @param $mobile
     * @param $member_id
     * @return array
     * @throws Exception
     */
    function createCustomer($username, $mobile, $member_id)
    {
        Db::startTrans();
        try {
            $add_data = [
                'customer_type' => 1,
                'customer_name' => $username,
                'avatar' => '/static/images/logo.png',
                'fullname' => $username,
                'mobile' => $mobile,
                'spread_type' => -1,
                'promoter' => 0,
                'status' => 1,
                'create_time' => date_now(),
                'update_time' => date_now(),
            ];

            $customer_id = model\Customer::insertGetId($add_data);

            if ($customer_id) {
                $con_data = [
                    'customer_id' => $customer_id,
                    'member_id' => $member_id,
                    'name' => $username,
                    'is_major' => 1,
                    'mobile' => $mobile,
                    'create_time' => date_now(),
                    'update_time' => date_now(),
                ];

                $contacts_id = model\CustomerContacts::insertGetId($con_data);

                if ($contacts_id) {
                    Db::commit();
                    return ['code' => 1, 'msg' => '创建客户成功', 'customer_id' => $customer_id, 'contacts_id' => $contacts_id];
                }
            }
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }

        return ['code' => 0, 'msg' => '创建客户失败'];
    }

}